package com.i2works.smartluolong.utils.config;

import org.apache.commons.lang3.StringUtils;
import org.beetl.core.resource.WebAppResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.ResourceUtils;

import java.io.IOException;

/**
 * 公共beelt配置
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2017/12/14 10:21
 */

public class BeetlConfigurationUtils {

    /**
     * 模板路径
     */
    private static final String TEMPLATES_PATH = "templates";
    /**
     * 配置文件
     */
    private static final String PROPERTIES_PATH = "config/beetl.properties";
    /**
     * 模板后缀
     */
    private static final String SUFFIX = ".html";

    /**
     * beetl配置器
     */
    public static BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration(String templatesPath, String propertiesPath) {
        if (StringUtils.isBlank(templatesPath)) {
            templatesPath = TEMPLATES_PATH;
        }
        if (StringUtils.isBlank(propertiesPath)) {
            propertiesPath = PROPERTIES_PATH;
        }
        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
        try {
            //指定beetl的根目录
            String root = patternResolver.getResource(ResourceUtils.CLASSPATH_URL_PREFIX + templatesPath).getFile().toString();
            WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(root);
            beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
            //加载beetl配置文件
            beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource(ResourceUtils.CLASSPATH_URL_PREFIX + propertiesPath));
            return beetlGroupUtilConfiguration;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * beetl视图解析器
     */
    public static BeetlSpringViewResolver getBeetlSpringViewResolver(BeetlGroupUtilConfiguration beetlGroupUtilConfiguration, String suffix) {
        if (StringUtils.isBlank(suffix)) {
            suffix = SUFFIX;
        }
        BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
        beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
        beetlSpringViewResolver.setSuffix(suffix);
        beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
        return beetlSpringViewResolver;
    }

}
